import axios from 'axios'
// npm install axios的时候默认会安装qs
// qs相关的问题请搜索"nodejs qs"或者看这里https://www.npmjs.com/package/qs
import qs from 'qs'
import { MessageBox, Message ,Notification } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'
import router from '@/router'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    config.data = config.data||{};
    config.errorCode = config.errorCode || {}
    // do something before request is sent
		if (getToken()!='') {
      // let each request carry token --['X-Token'] as a custom key.
      // please modify it according to the actual situation.
         config.headers['token'] = getToken()
         config.data['token'] = getToken()
    }
    if (config.method.toLocaleLowerCase() === 'post') {
      config.headers['content-type'] = 'application/x-www-form-urlencoded;charset=utf-8'
      config.data = qs.stringify(config.data)
    }
    // console.log(config);
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

const errorCode = {
  "1000"(res){
    Message({
      message: '登录超时',
      type: 'error',
      duration: 5 * 1000
    })
    setTimeout(function () {
      removeToken();
      var path = '/login?redirect=' + router.currentRoute.fullPath;
      router.replace({path: path})
    }, 1000)
  }
}

export default service

